/**
 * Created by arvin on 2017/4/10.
 */
/**
 这个是保留接口，方便我处理数据库
 */
var Bearcat = require('bearcat');
var Async = require("async")

module.exports = function () {
    return Bearcat.getBean({
        id: "get-admin",
        func: admin,
        props: [
            {name: "app", "ref": "application"}
        ]
    });
}

function admin() {
    this.app = null;
}

var CheckMotionDevice = function (msg) {
    if(msg.params.motion == undefined || msg.params.admin == undefined)
        return false;
    //  if(msg.params.motion.length != 40)
    //    return false;
    return true;
}

admin.prototype.handle = function (msg,next) {

   // if(!CheckMotionDevice(msg))
    {
        next(null,{code:101,msg:110});
        return;
    }

    var admin = msg.params.admin;
    var motion = msg.params.motion;
    var pwd = msg.params.pwd;
    var model = this.app.getComponent("dao").getConnection().model("adminMsg");
    Async.waterfall(
        [
            function () {
                model.invalidate(motion,function (invalid) {
                    if(invalid) // 查询到，表示有，就更新
                    {
                        model.UpdateAdmin(motion);
                    }
                    else // 没查询到，表示没有，就信加入一个
                    {
                        model.addMotionDev(
                            {   MotionDevice: motion,
                                Admin : admin,
                                UsedTime: 0,
                                Password :pwd
                            }
                            );
                    }
                })
                next(null,{code:1,msg:"update admin over"});
            }
        ]
    );
}